package com.le.tester.imooc.masterJUC.lock.deadlock;

/**
 * 描述：必定会发生死锁
 */
public class MustDeadLock implements Runnable {

    int flag = 1;

    static final Object o1 = new Object();
    static final Object o2 = new Object();

    public static void main(String[] args) {
        MustDeadLock mustDeadLock0 = new MustDeadLock();
        MustDeadLock mustDeadLock1 = new MustDeadLock();
        mustDeadLock0.flag = 0;
        mustDeadLock1.flag = 1;

        new Thread(mustDeadLock0).start();
        new Thread(mustDeadLock1).start();
    }

    @Override
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("线程1锁住了o1");
                }
            }

        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("线程2锁住了o2");
                }
            }
        }
    }
}
